package com.sergio.compress.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

/**
 * @Author : Sergio.D
 * @Description :
 * @CreateDate ：2023/6/16 13:19
 */
@Slf4j
public class PythonUtil {

    private static final String PY_PATH = "./pythons/";

    public static void execPySimple(String pythonName) {
        execPySimple(pythonName, "");
    }

    public static void execPySimple(String pythonName, String param) {
        String pythonCommand = "python3 " + PY_PATH + pythonName + " " + param;
        String pyResult = "";
        try {
            // 调用 Python 脚本
            log.info(DateUtil.convertDate2String(new Date()) + "执行python : " + pythonCommand + " ");
            Process process = Runtime.getRuntime().exec(pythonCommand);
            // 使用管道进行输入/输出
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            // 从 Python 脚本读取数据
            String line = "";
            while ((line = in.readLine()) != null) {
                System.out.println(line);
                if (StringUtils.isNotBlank(line)) {
                    pyResult = line;
                }
            }
            log.info(DateUtil.convertDate2String(new Date()) + " python 执行结果 : " + pyResult + " ");
            // 关闭流
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("执行 python  [ " + pythonCommand + " ] 执行结果失败 : " + pyResult + " 发生错误 : " + e.getMessage());
        }
    }

    public static <T> T execPython(String pythonName, String param, Class<T> resultClass) {
        T result = null;
        String pythonCommand = "python3 " + PY_PATH + pythonName + " " + param;
        String pyResult = "";
        try {
            // 调用 Python 脚本
            log.info("执行python : " + pythonCommand + " " + DateUtil.convertDate2String(new Date()));
            Process process = Runtime.getRuntime().exec(pythonCommand);
            // 使用管道进行输入/输出
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            // 从 Python 脚本读取数据
            String line = "";
            while ((line = in.readLine()) != null) {
                System.out.println(line);
                if (StringUtils.isNotBlank(line)) {
                    pyResult = line;
                }
            }
            log.info(DateUtil.convertDate2String(new Date()) + " python 执行结果 : " + pyResult + " ");
            // 关闭流
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("执行 python  [ " + pythonCommand + " ] 执行结果失败 : " + pyResult + " 发生错误 : " + e.getMessage());
            return result;
        }
    }
}
